import commonUtil from './commonUtil.js';
import AESUtil from './aes-util';
var peihuyiAesUtil = require("./aes.js");
const _hex = require('lagden-hex'); // 载入第三方 npm 模块
import CRC16 from 'CRC16';
import util from './util';

const baseVer = wx.getSystemInfoSync().SDKVersion
const sysInfo = wx.getSystemInfoSync()
var a;
//陪护椅相关参数名
function e(e, a, o) {
    return a in e ? Object.defineProperty(e, a, {
        value: o,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : e[a] = o, e;
}

var BleTool = {
    status: {
        //已连接
        CONNECTED: 'connnected',
        //蓝牙断开
        DIS_CONNECT: 'disConnect',
        DATA_95: '95data',
        DATA_85_FIRST: '85dataFirst',
        DATA_85_SECOND: '85dataSecond',
    },
    bleName: '',
    macId: '',
    //命令的序列号
    cmdSeq: 0,
    _Device: null,
    // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
    deviceId: null,
    // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
    serviceId: null,
    char6UUID: null,
    _WXWriteUUID: null,
    //陪护椅读通道uuid
    peihuyiReadUUID: "000036F6-0000-1000-8000-00805F9B34FB",
    //当前设备是否为陪护椅
    curDevIsPeihuyi: false,
    miniAuthSetting: null,
    //陪护椅蓝牙参数信息
    peihuyiBleVariable: (a = {
            mMacAddress: "",
            mDrawerMacAddress: "",
            unlockPwd: "",
            drawerUnlockPwd: "",
            cmds: {
                getTokenCmd: [6, 1, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
                queryLockStatusCmd: [5, 14, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
                queryBatteryCmd: [2, 1, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
                unlockCmd: [5, 1, 6, 48, 48, 48, 48, 48, 48, 12, 12, 12, 12, 12, 12, 12],
                lockCmd: [5, 12, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12]
            },
            dataPrefix: {
                getTokenPrefix: "6,2",
                queryLockStatusPrefix: "5,15",
                queryLockBatteryPrefix: "2,2",
                unlockPrefix: "5,2",
                lockPrefix: "5,8",
                lockPrefix2: "5,13",
                deviceDisconnectPrefix: "5,23",
                unknowCmdPrefix: "5,3"
            },
            action: {
                actionUnlock: 1,
                actionLock: 2
            },
            errCode: {
                errTokenErr: 1
            },
            errContent: {
                errTokenErrContent: "Token错误"
            },
            currAction: 0,
            akey: [58, 96, 67, 42, 92, 1, 33, 31, 41, 30, 15, 78, 12, 19, 40, 37],
            netWorkAKey: [110, 100, 220, 70, 41, 71, 219, 232, 73, 168, 149, 228, 26, 189, 253, 209]
        }, e(a, "unlockPwd", [48, 48, 48, 48, 48, 48]), e(a, "drawerUnlockPwd", [48, 48, 48, 48, 48, 48]),
        e(a, "aiv", []), e(a, "keyBv", null), e(a, "ivBv", null), e(a, "keyWA", null), e(a, "ivWA", null),
        e(a, "mDeviceId", ""), e(a, "serviceId", "0000FEE7-0000-1000-8000-00805F9B34FB"),
        e(a, "services", []), e(a, "cdRead", "000036F6-0000-1000-8000-00805F9B34FB"), e(a, "cdWrite", "000036F5-0000-1000-8000-00805F9B34FB"),
        e(a, "UUID_SERVER", "0000FEE7-0000-1000-8000-00805F9B34FB"), e(a, "isDeviceFound", !1),
        e(a, "isConnected", !1), e(a, "isCommuOver", !0), e(a, "scanDeviceOverTime", 2e4),
        e(a, "connectDeviceOverTime", 12e3), e(a, "commuDeviceOverTime", 12e3), e(a, "commuDeviceOverTimeRetryCnt", 3),
        e(a, "token", [0, 0, 0, 0]), a),

    /**
     * 初始化数据
     */
    init: function () {
        BleTool.belLog("初始化蓝牙相关参数")
        bleData.init()
        this.cmdSeq = 0
        this._Device = null
        this.deviceId = null
        this.serviceId = null
        this.char6UUID = null
        this._WXWriteUUID = null
    },
    belLog: console.log,
    //状态处理
    handleStatus: function (status, data) {},
    validateBleAuth: function () {
        //检查系统权限
        const sysSetting = this.getSysSetting(baseVer)
        if (sysSetting != null) {
            if (!sysSetting.bluetoothEnabled) {
                wx.showToast({
                    title: '系统蓝牙未打开',
                })
                return 'sys_ble_' + sysInfo.platform
            }
            if (!sysSetting.locationEnabled) {
                wx.showToast({
                    title: '系统定位未打开',
                })
                return 'sys_location'
            }
        }

        //检查微信授权情况
        const appAuthSetting = this.getAppAuthSetting(baseVer)
        if (appAuthSetting != null) {
            if (appAuthSetting.locationAuthorized != 'authorized') {
                //微信不能使用定位权限
                wx.showToast({
                    title: '微信定位未授权',
                })
                return 'wx_location'
            }
            if (sysInfo.platform == 'ios' && appAuthSetting.bluetoothAuthorized != 'authorized') {
                wx.showToast({
                    title: '微信蓝牙未授权',
                })
                return 'wx_ble'
            }
        }

        //检查微信小程序授权情况
        this.getMiniSetting(baseVer)
        
        return 'pass'
    },
    /**
     * 获取系统配置信息
     * @param {*} baseVer 
     */
    getSysSetting: function (baseVer) {
        let verRst = commonUtil.compareVersion(baseVer, '2.20.1')
        if (verRst >= 0) {
            return wx.getSystemSetting()
        }
        return null
    },
    /**
     * 获取app授权配置
     * @param {*} baseVer 
     */
    getAppAuthSetting: function (baseVer) {
        let verRst = commonUtil.compareVersion(baseVer, '2.20.1')
        if (verRst >= 0) {
            return wx.getAppAuthorizeSetting()
        }
        return null
    },
    /**
     * 获取小程序的授权配置
     */
    getMiniSetting: function (baseVer) {
        let verRst = commonUtil.compareVersion(baseVer, '1.2.0')
        if (verRst >= 0) {            
            wx.getSetting({
                success(res) {
                    BleTool.belLog("小程序授权信息:", res)
                    BleTool.miniAuthSetting = res.authSetting
                }
            })
        }
    },
    /**
     * 获取已连接的蓝牙设备
     */
    getConnectedBluetoothDevices: function (callback) {
        wx.getConnectedBluetoothDevices({
            services: ['FEE7'],
            success: function (res) {
                callback(res.devices)
            },
            fail: function (err) {
                callback(null)
            }
        })
    },
    closeBLEConnection: function (devId) {
        wx.closeBLEConnection({
            deviceId: devId,
            success(res) {}
        })
    },
    openBleAdapter: function () {
        let that = this
        let verRst = commonUtil.compareVersion(baseVer, '1.1.0')
        if (verRst >= 0) {
            that.onBleAdapterStateChange()
            BleTool.belLog("打开蓝牙适配器")
            wx.openBluetoothAdapter({
                success(res) {
                    BleTool.belLog("打开蓝牙适配器调用成功")
                    //判断当前是否蓝牙连接着
                    that.getConnectedBluetoothDevices(function (devices) {
                        BleTool.belLog("获取已连接的设备信息:", devices)
                        if (devices && devices.length > 0) {
                            //已连接设备
                            let isExists = false
                            for (var i = 0; i < devices.length; i++) {
                                let devId = devices[i].deviceId
                                if (devId == that.deviceId) {
                                    //同一个连接，可直接发送相关命令
                                    isExists = true
                                } else {
                                    that.closeBLEConnection(devId);
                                }
                            }
                            if (isExists) {
                                //同一个连接，可直接发送相关命令
                                that.send95Cmd()
                            } else {
                                //连接非同一个连接，需断开连接重连
                                setTimeout(function () {
                                    BleTool.init()
                                    that.onFundBleEqu();
                                    that.scanBle();
                                }, 500);
                            }
                        } else if (!devices) {
                            BleTool.init()
                            //调用连接失败
                            wx.showToast({
                                title: '连接调用失败',
                            })
                        } else {
                            BleTool.init()
                            that.onFundBleEqu();
                            that.scanBle();
                        }
                    })
                },
                fail(err) {
                    if(BleTool.miniAuthSetting != null) {
                        
                        if(!BleTool.miniAuthSetting['scope.bluetooth']) {
                            wx.showModal({
                                title: '提示',
                                content: '去打开小程序蓝牙权限',
                                success(res) {
                                    if (res.confirm) {
                                        wx.openSetting({
                                            success(res) {
                                                console.log(res.authSetting)
                                                BleTool.miniAuthSetting = res.authSetting
                                            }
                                        })
                                    } else if (res.cancel) {
                                        BleTool.belLog('用户点击取消授权')
                                    }
                                }
                            })
                        }
                        
                    }else if (sysInfo.platform == 'ios') {
                        if (err.state == 3) {
                            //微信未授权
                            wx.showToast({
                                title: '蓝牙未授权',
                            })
                        } else if (err.state == 4) {
                            //系统蓝牙未开启
                            wx.showToast({
                                title: '蓝牙未打开',
                            })
                        } else {
                            let showTitle = ''
                            switch (err.state) {
                                case 0:
                                    showTitle = '未知'
                                    break
                                case 1:
                                    showTitle = '重置中'
                                    break
                                case 2:
                                    showTitle = '不支持'
                            }
                            wx.showToast({
                                title: showTitle,
                            })
                        }
                    } else {                       
                        if (err.errCode == 10001) {
                            wx.showToast({
                                title: '蓝牙未开启',
                            })
                        } else {
                            wx.showToast({
                                title: err.errCode ? err.errCode : '蓝牙打开失败',
                            })
                        }
                    }
                }
            })
        } else {
            wx.showToast({
                title: '版本太低',
            })
        }
        return null
    },
    /**
     * 监听蓝牙适配器状态变化
     */
    onBleAdapterStateChange: function () {
        BleTool.belLog("监听蓝牙适配器状态")
        let that = this
        wx.onBluetoothAdapterStateChange(function (res) {
            BleTool.belLog('adapterState changed, now is', res)
            if (res.discovering === true) {
                //适配器搜索中
                BleTool.belLog("适配器搜索中....")
            }
            if (res.available === true) {
                //蓝牙适配器可用,发起扫描
                BleTool.belLog("适配器可以用")

            }
        })
    },
    /**
     * 扫描设备
     */
    scanBle: function () {
        BleTool.belLog("扫描设备")
        //考虑到蓝牙功能可以间接进行定位，安卓 6.0 及以上版本，无定位权限或定位开关未打开时，无法进行设备搜索。这种情况下，安卓 8.0.16 前，接口调用成功但无法扫描设备；8.0.16 及以上版本，会返回错误        
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true,
            success(res) {
                BleTool.belLog(res)
            },
            fail: function (err) {
                wx.showModal({
                    title: '提示',
                    content: '扫描设备调用失败:' + err.errCode,
                    showCancel: false,
                    success(res) {}
                })
            }
        })
    },
    /**
     * 扫描发现设备
     */
    onFundBleEqu: function () {
        BleTool.belLog("发现设备")
        let that = this
        wx.onBluetoothDeviceFound(function (res) {
            var devices = res.devices;
            for (var i = 0; i < devices.length; i++) {
                var device = devices[i]
                let advertisData = ab2hex(device.advertisData);
                let adName = null;
                let adMac = null;
                if (advertisData) {
                    let head = advertisData.substring(0, 4);
                    if (head > 5701) {
                        let adMacName = advertisData.substring(4, 12);
                        adName = 'DK' + adMacName.toUpperCase();
                    }

                    if (advertisData.length >= 16) {
                        let devName = advertisData.substring(4, 6) + ":" + advertisData.substring(6, 8) + ":" + advertisData.substring(8, 10) + ":" + advertisData.substring(10, 12) + ":" + advertisData.substring(12, 14) + ":" + advertisData.substring(14, 16);
                        adMac = devName.toUpperCase();
                    }
                }
                let devName = device.name ? device.name : null;
                let localName = device.localName ? device.localName : null;

                if (that.bleName && (that.bleName == devName || that.bleName == localName || that.bleName == adName || that.bleName == adMac)) {
                    BleTool.belLog("on found ble ", devName, localName, device, that.bleName);
                    that._Device = device
                    that.deviceId = device.deviceId
                    that.stopDiscoveryBle()
                    that.createBleCon()
                    break;
                }
            }

        })
    },
    /**
     * 停止搜索
     */
    stopDiscoveryBle: function () {
        wx.stopBluetoothDevicesDiscovery({
            success(res) {
                BleTool.belLog(res)
            }
        })
    },
    /**
     * 创建蓝牙连接
     */
    createBleCon: function () {
        let that = this
        that.listenBleConStateChange()
        wx.createBLEConnection({
            deviceId: that.deviceId,
            timeout: 10000,
            success(res) {
                BleTool.belLog("【蓝牙连接】蓝牙连接成功");
                BleTool.handleStatus(BleTool.status.CONNECTED, null)
            },
            fail(err) {
                wx.showModal({
                    title: '提示',
                    content: '连接调用失败:' + err.errCode,
                    showCancel: false,
                    success(res) {}
                })
            }
        })
    },
    /**
     * 监听蓝牙连接状态
     */
    listenBleConStateChange: function () {
        let that = this
        wx.onBLEConnectionStateChange(function (res) {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            BleTool.belLog(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            if (res.connected) {
                that.getBLEDeviceServices()
            }else {
                BleTool.handleStatus(BleTool.status.DIS_CONNECT, null)
            }
        })
    },
    getBLEDeviceServices: function () {
        let that = this
        wx.getBLEDeviceServices({
            // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立连接
            deviceId: that.deviceId,
            success(res) {
                BleTool.belLog('device services:', res.services)
                for (var t = 0; t < res.services.length; t++) {
                    if (-1 != res.services[t].uuid.toUpperCase().indexOf("0000FEE7")) {
                        that.serviceId = res.services[t].uuid
                        break;
                    }
                }

                that.getBLEDeviceCharacteristics()
            }
        })

    },
    getBLEDeviceCharacteristics: function () {
        let that = this
        wx.getBLEDeviceCharacteristics({
            // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
            deviceId: that.deviceId,
            // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
            serviceId: that.serviceId,
            success(res) {
                BleTool.belLog('device getBLEDeviceCharacteristics:', res.characteristics)
                let count = 0;
                for (var t = 0; t < res.characteristics.length; t++) {
                    if (-1 != res.characteristics[t].uuid.toUpperCase().indexOf("FEC8")) {
                        that.char6UUID = res.characteristics[t].uuid
                        count++;
                    } else if (-1 != res.characteristics[t].uuid.toUpperCase().indexOf("FEC7")) {
                        that._WXWriteUUID = res.characteristics[t].uuid
                        count++;
                    } else if (res.characteristics[t].properties.write) {
                        //写数据通道
                        that._WXWriteUUID = res.characteristics[t].uuid
                        BleTool.belLog("写数据通道->", that._WXWriteUUID)
                    } else if (res.characteristics[t].properties.notify) {
                        //读数据通道
                        that.char6UUID = res.characteristics[t].uuid
                        BleTool.belLog("读数据通道->", that.char6UUID)
                    }
                    if (count == 2) {
                        break;
                    }
                }

                that.notifyBLECharacteristicValueChanged()
            }
        })
    },
    notifyBLECharacteristicValueChanged: function () {
        let that = this
        wx.notifyBLECharacteristicValueChanged({
            deviceId: that.deviceId,
            serviceId: that.serviceId,
            characteristicId: that.char6UUID,
            state: true,
            success: function (res) {
                that.onBLECharacteristicValueChange()
                BleTool.belLog('device notifyBLECharacteristicValueChanged:', that.char6UUID, BleTool.peihuyiReadUUID)

                that.curDevIsPeihuyi = that.char6UUID == BleTool.peihuyiReadUUID
                if (that.curDevIsPeihuyi) {
                    BleTool.belLog("陪护椅发送获取token")
                    setTimeout(function () {
                        that.sendPeihuyiBleGetToken();
                    }, 1200);
                }
            },
            fail: function (err) {
                BleTool.belLog("notifyBLECharacteristicValueChanged fail", err);
                wx.showModal({
                    title: '提示',
                    content: '通知调用失败:' + err.errCode,
                    showCancel: false,
                    success(res) {}
                })
            }
        })
    },

    onBLECharacteristicValueChange: function () {
        let that = this
        wx.onBLECharacteristicValueChange(function (characteristic) {
            const hex = buf2hex(characteristic.value).toUpperCase()
            BleTool.belLog("【=====================接收到设备发来的数据】", hex, "isPeihuyi:" + that.curDevIsPeihuyi)
            if (that.curDevIsPeihuyi) {
                bleData.parsePeihuyiValue(characteristic)
            } else {
                that.handleBleData(hex)
            }
        })
    },

    handleBleData: function (hex) {
        let that = this
        var command;
        if (hex.indexOf("E5") == 0 && !that.receiveHex) {
            that.receiveLen = parseInt(hex.substring(2, 4), 16) + 2;
            command = hex.substring(8, 10); //指令
        }

        that.receiveHex = (that.receiveHex ? that.receiveHex : '') + hex
        BleTool.belLog("接收数据---receiveHex-》", that.receiveHex, that.receiveLen)

        if (command == '01' && that.receiveLen == 19) {
            BleTool.belLog('【蓝牙连接】处理收到的随机数：', hex);
            let flg = validateCrc16Code(hex);
            if (!flg) {
                BleTool.belLog("【蓝牙连接】随机数校验码失败");
                return;
            }
            //随机数
            that.randomStr = hex.substring(10, 18);
            that.driverVer = hex.substring(18, 34);
            that.equType = hex.substring(18, 20);
            that.isOld = false
            BleTool.belLog('【蓝牙连接】收到的随机数：', that.randomStr, that.driverVer);
            that.receiveHex = null
            that.receiveLen = null
        } else if (that.randomStr && that.randomStr.length > 0) {
            //检查是否已接收完普通数据
            BleTool.belLog("检查数据是否接收完成-", that.receiveLen, that.receiveHex.length)
            that.checkReceiveData()
        }
    },

    checkReceiveData: function () {
        let that = this
        if (that.receiveHex.length >= that.receiveLen * 2) {
            BleTool.belLog("数据接收完成-->", that.receiveHex)
            let isOld = bleData.isOld;
            if (isOld) {
                bleData.parseData();
                that.receiveHex = null;
                that.receiveLen = null;
                return;
            }
            //校验CRC16
            let flg = validateCrc16Code(that.receiveHex);
            if (!isOld && !flg) {
                BleTool.belLog("【蓝牙连接】数据CRC16校验失败，无法处理");
                return;
            }
            let app = getApp()
            if (bleData.blePwd) {
                bleData.parseData();
                that.receiveHex = null;
                that.receiveLen = null;
                return;
            } else {
                //重新获取秘钥
                wx.request({
                    url: util.CONST_DATA.BASE_URL + 'ble/pwd',
                    data: {
                        mac: BleTool.macId,
                        random: that.randomStr
                    },
                    header: app.globalData.header,
                    method: 'post',
                    success: function (res) {
                        if (res.data.result == 0) {
                            let pwd = res.data.data;
                            bleData.blePwd = pwd;
                            bleData.parseData();
                            that.receiveHex = null;
                            that.receiveLen = null;
                            return;
                        } else {
                            wx.showModal({
                                title: '提示',
                                content: '连接秘钥错误',
                                showCancel: false,
                                success(res) {}
                            })
                        }
                    },
                    fail: function () {
                        wx.showModal({
                            title: '提示',
                            content: '连接秘钥API调用失败',
                            showCancel: false,
                            success(res) {}
                        })
                    }
                })
            }
        } else {
            BleTool.belLog("继续接收数据:", that.receiveLen, that.receiveHex.length)
        }
    },

    /**
     * 蓝牙连接
     */
    connect: function () {

        //检验权限是否开启
        const isAuth = this.validateBleAuth()
        BleTool.belLog("权限校验结果:", isAuth)
        if (isAuth == 'pass') {
            //开启适配器
            this.openBleAdapter()
        } else if (isAuth == 'sys_ble_android') {
            //系统蓝牙未打开跳转到对应页面
            wx.showModal({
                title: '提示',
                content: '去打开系统蓝牙权限',
                success(res) {
                    if (res.confirm) {
                        wx.openSystemBluetoothSetting({
                            success(res) {
                                BleTool.belLog("打开系统蓝牙配置", res)
                            }
                        })
                    } else if (res.cancel) {
                        BleTool.belLog('用户点击取消')
                    }
                }
            })
        }else if (isAuth == 'sys_ble_android') {
            wx.showModal({
                title: '提示',
                content: '去打开系统蓝牙权限',
                success(res) {                    
                }
            })
        }else if (isAuth == 'wx_location' || isAuth == 'wx_ble') {
            wx.showModal({
                title: '提示',
                content: isAuth == 'wx_location' ? '去打开微信定位权限' : '去打开微信蓝牙权限',
                success(res) {
                    if (res.confirm) {
                        wx.openAppAuthorizeSetting({
                            success(res) {
                                BleTool.belLog(res)
                            }
                        })
                    } else if (res.cancel) {
                        BleTool.belLog('用户点击取消')
                    }
                }
            })

        } else {
          
        }

    },
    /**
     * 发送自定义命令
     */
    sendCustomCmd:function(inputCmd) {
       let cmdHex = createSendMessage(inputCmd, true)
       this.sendCmd(cmdHex)
    },
    /**
     * 发送命令
     */
    sendCmd: function (hex) {
        let that = this
        var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
            return parseInt(h, 16)
        }))
        var buffer = typedArray.buffer
        that.writeBLECharacteristicValue(buffer)
    },
    writeBLECharacteristicValue: function (buffer) {
        let that = this
        this.receiveHex = null
        this.receiveLen = null
        wx.writeBLECharacteristicValue({
            deviceId: that.deviceId,
            serviceId: that.serviceId,
            characteristicId: that._WXWriteUUID,
            value: buffer,
            success: function (res) {
                BleTool.belLog("【wx.writeBLECharacteristicValue】【发送数据成功】")
            },
            fail: function (res) {
                console.error("【error】【wx.writeBLECharacteristicValue】【发送数据失败】", res)
                wx.showModal({
                    title: '提示',
                    content: '发送失败:' + err.Msg + ':' + err.errCode,
                    showCancel: false,
                    success(res) {}
                })
            }
        })
    },
    send95Cmd: function () {
        BleTool.belLog("发送95数据------->")
        let sendHexStr = createSendMessage('95', '01')
        this.sendCmd(sendHexStr)
    },
    send85Cmd: function () {
        BleTool.belLog("发送88数据------->")
        let sendHexStr = createSendMessage('88')
        this.sendCmd(sendHexStr)
    },

    /**
     * 获取陪护椅的token
     */
    sendPeihuyiBleGetToken: function () {
        let that = this
        BleTool.belLog("bleGetToken");
        for (var a = 0; a < that.peihuyiBleVariable.cmds.getTokenCmd.length; a++) a <= 3 || (that.peihuyiBleVariable.cmds.getTokenCmd[a] = Math.round(100 * Math.random()));
        let sendCmd = that.peihuyiBleVariable.cmds.getTokenCmd;
        that.sendPeihuyiCmd(sendCmd)
    },
    //查询one more陪护椅的电量
    queryPeihuyiBattery: function () {
        let that = this
        BleTool.belLog("queryBattery");
        for (var a = 0; a < that.peihuyiBleVariable.cmds.queryBatteryCmd.length; a++) a <= 3 || (that.peihuyiBleVariable.cmds.queryBatteryCmd[a] = a >= 4 && a <= 7 ? that.peihuyiBleVariable.token[a - 4] : Math.round(100 * Math.random()));
        let sendCmd = that.peihuyiBleVariable.cmds.queryBatteryCmd;
        that.sendPeihuyiCmd(sendCmd)
    },
    queryPeihuyiLockStatus: function () {
        let that = this
        BleTool.belLog("queryLockStatus");
        for (var a = 0; a < that.peihuyiBleVariable.cmds.queryLockStatusCmd.length; a++) a <= 3 || (that.peihuyiBleVariable.cmds.queryLockStatusCmd[a] = a >= 4 && a <= 7 ? that.peihuyiBleVariable.token[a - 4] : Math.round(100 * Math.random()));
        let sendCmd = that.peihuyiBleVariable.cmds.queryLockStatusCmd;
        that.sendPeihuyiCmd(sendCmd)
    },
    //宜家陪护椅开锁发送命令
    oneMorePhyBleUnlock: function () {
        let that = this
        for (var a = 0; a < that.peihuyiBleVariable.cmds.unlockCmd.length; a++) a <= 2 || (a >= 3 && a <= 8 ? true ? that.peihuyiBleVariable.cmds.unlockCmd[a] = that.peihuyiBleVariable.unlockPwd[a - 3] : that.peihuyiBleVariable.cmds.unlockCmd[a] = that.peihuyiBleVariable.drawerUnlockPwd[a - 3] : that.peihuyiBleVariable.cmds.unlockCmd[a] = a >= 9 && a <= 12 ? that.peihuyiBleVariable.token[a - 9] : Math.round(100 * Math.random()));
        let cmdUnlock = that.peihuyiBleVariable.cmds.unlockCmd
        console.log("宜家陪护椅开始开锁", cmdUnlock);
        that.sendPeihuyiCmd(cmdUnlock)
    },
    //发送陪护椅命令
    sendPeihuyiCmd: function (sendCmd) {
        var that = this
        BleTool.belLog("【发送陪护椅token指令】开始发送数据...", sendCmd)
        sendCmd = that.peihuyiAesEncrypt(sendCmd);
        BleTool.belLog("Before Encrypt binary array is" + sendCmd);
        that.writeBLECharacteristicValue(sendCmd.buffer)
    },


    /**
     * 陪护椅命令加密
     */
    peihuyiAesEncrypt: function (cmd) {
        let that = this
        cmd = new Int8Array(cmd);
        BleTool.belLog("Encrypt acontent is " + cmd);
        let keyBv = new Int8Array(that.peihuyiBleVariable.akey)
        let ivBv = new Int8Array(that.peihuyiBleVariable.aiv)
        let keyWA = peihuyiAesUtil.CryptoJS.enc.int8array.parse(keyBv)
        let ivWA = peihuyiAesUtil.CryptoJS.enc.int8array.parse(ivBv)
        var l = peihuyiAesUtil.CryptoJS.enc.int8array.parse(cmd)
        var t = peihuyiAesUtil.CryptoJS.AES.encrypt(l, keyWA, {
            iv: ivWA,
            mode: peihuyiAesUtil.CryptoJS.mode.ECB,
            padding: peihuyiAesUtil.CryptoJS.pad.NoPadding
        });
        return peihuyiAesUtil.CryptoJS.enc.int8array.stringify(t.ciphertext);
    },
    /**
     * 陪护椅解析数据
     */
    peihuyiAesDecrypt: function (receiveData) {
        let that = this
        let keyBv = new Int8Array(that.peihuyiBleVariable.akey)
        let ivBv = new Int8Array(that.peihuyiBleVariable.aiv)
        let keyWA = peihuyiAesUtil.CryptoJS.enc.int8array.parse(keyBv)
        let ivWA = peihuyiAesUtil.CryptoJS.enc.int8array.parse(ivBv)
        var rData = peihuyiAesUtil.CryptoJS.enc.int8array.parse(receiveData).toString(peihuyiAesUtil.CryptoJS.enc.Base64);
        var decData = peihuyiAesUtil.CryptoJS.AES.decrypt(rData, keyWA, {
            iv: ivWA,
            mode: peihuyiAesUtil.CryptoJS.mode.ECB,
            padding: peihuyiAesUtil.CryptoJS.pad.NoPadding
        });
        decData = peihuyiAesUtil.CryptoJS.enc.int8array.stringify(decData)
        BleTool.belLog("Decrypt decrypted is ", decData);
        return decData
    }

}
var bleData = {
    randomStr: null,
    driverVer: null,
    equType: null,
    isOld: false,
    data88: null,
    data95: null,
    data95: null,
    data98: null,
    blePwd: null,
    //陪护椅锁具数据
    _DataOneMorePhyLock: null,

    init: function () {
        this._DataOneMorePhyLockBattery = null;
        this.randomStr = null;
        this.driverVer = null;
        this.equType = null;
        this.isOld = null;
        this.data88 = null;
        this.data95 = null;
        this.data95 = null;
        this.data98 = null;
        this.blePwd = null;
    },
    parseData: function () {
        let that = this
        let businessStr = BleTool.receiveHex;
        let receiveDeData = null;
        let cmdId = null
        if (!that.isOld) {
            BleTool.belLog('【蓝牙连接】完整业务数据： isBusinessDataReceiveCompleted  received business data ', businessStr);
            let enData = businessStr.substring(4, businessStr.length - 4);
            let deData = AESUtil.aesDecryptByPwd(that.blePwd, enData);
            businessStr = businessStr.substring(0, 4) + deData + businessStr.substring(businessStr.length - 4);
            BleTool.belLog("【接收普通数据】解密后的数据：", businessStr)
            cmdId = businessStr.substring(8, 10);
            receiveDeData = businessStr
        } else {
            let size = businessStr.substring(22, 24);
            BleTool.belLog('【蓝牙连接old】变长包数据长度： isBusinessDataReceiveCompleted  received business data: 1', size, parseInt(size, 16));
            businessStr = businessStr.substring(0, (12 + parseInt(size, 16)) * 2);
            BleTool.belLog('【蓝牙连接old】有效业务数据：isBusinessDataReceiveCompleted  received business data 2 ', businessStr);
            businessStr = businessStr.substring(48, (12 + parseInt(size, 16)) * 2);
            BleTool.belLog('【蓝牙连接old】最终业务数据： isBusinessDataReceiveCompleted  received business data 3', businessStr);
            let result = _hex.decode(businessStr, false);
            let arr = result.split(',');
            BleTool.belLog('【蓝牙连接old】业务数据数组：', arr);
            cmdId = arr[0];
            receiveDeData = arr
        }
        console.info('【蓝牙连接】cmdId：', cmdId);

        let bussinessData = {
            cmdId: cmdId
        };
        if (cmdId == '85' || cmdId == '88') {
            bussinessData.cmdId = '88'
            bussinessData.data = that.parseData85(receiveDeData, true)
        } else if (cmdId == '95') {
            bussinessData.data = that.parseData95(receiveDeData);
        } else if (cmdId == '98') {
            bussinessData.data = that.parseData98(receiveDeData);
        } else {
            bussinessData = businessStr;
            BleTool.belLog('【蓝牙连接】未进行格式化的指令：', cmdId);
        }

        if (bussinessData.cmdId == "88") { //85指令响应数据      
            that.data88 = bussinessData.data
            BleTool.belLog("【接收普通数据】88指令响应数据", that.data88)
        } else if (bussinessData.cmdId == "85") { //85指令响应数据      
            that.data88 = bussinessData.data
            BleTool.belLog("【接收普通数据】85指令响应数据", that.data88)
        } else if (bussinessData.cmdId == "95") { //95指令响应数据      
            that.data95 = bussinessData.data
            that.data95.pile_ver = BleTool.driverVer
            BleTool.belLog("【接收普通数据】95指令响应数据", that.data95)
        } else if (bussinessData.cmdId == "98") { //95指令响应数据      
            that.data98 = bussinessData.data
            BleTool.belLog("【接收普通数据】98指令响应数据", that.data98)
        } else {
            BleTool.belLog("【蓝牙连接】未处理的响应数据", bussinessData);
        }
    },

    //解析85数据
    parseData85(data, transferOpenLockCmd) {
        let _Data85 = null;
        if (data.length < 4) {
            console.info('【蓝牙连接】无效的85响应数据', data);
            return null; + 9
        }

        _Data85 = new Object();
        if (transferOpenLockCmd) {
            _Data85.command = '85'; //指令
        } else {
            _Data85.command = parseInt(data[0]); //指令
        }
        if (!isArrayFn(data)) {
            //新固件
            _Data85.isNew = 1;
            _Data85.backSeq = data.substring(10, 12);
            if (_Data85.backSeq == 1) {
                //控制盒接收到命令
                _Data85.motorStat = data.substring(12, 14);
                _Data85.mac = data.substring(14, 26);
                _Data85.diffTime = data.substring(26, 32);
            } else if (_Data85.backSeq == 2) {
                //开锁完成
                _Data85.motorRunningTime = data.substring(24, 26);
                _Data85.rfid = data.substring(26, 34);
                _Data85.lockStat = data.substring(34, 36);
                _Data85.insertStat = data.substring(36, 38);
                _Data85.lockErrCode = data.substring(38, 40);
                _Data85.noEject = data.substring(40, 42);
            }
        } else {
            _Data85.isNew = 0;

            //191101 之后的驱动
            if (_Data95 && _Data95.pile_ver && _Data95.pile_ver.slice(-6) >= '191101') { //两次85回执
                _Data85.isNew = 2; //新新驱动
                _Data85.backSeq = parseInt(data[1])
                if (_Data85.backSeq == 1) { //立即返回指令
                    _Data85.motorStat = data[2]; //马达运行状态 00正常  01正在运行
                    _Data85.mac = data[3]; //设备MAC地址
                    _Data85.diffTime = data[4]; //这个轮椅在此桩上待的时间（分钟）
                } else if (_Data85.backSeq == 2) { //开锁后返回指令
                    _Data85.mac = data[2]; //设备MAC地址
                    _Data85.motorRunningTime = data[3]; //马达运行时间（秒）
                    _Data85.rfid = data[4]; //rfid
                    _Data85.lockStat = data[5]; //锁钩开关状态
                    _Data85.insertStat = data[6]; //插入开关状态
                    _Data85.lockErrCode = data[7]; //开锁错误码
                    _Data85.noEject = data[8]; //设备没弹出标记 0弹出  1未弹出
                    _Data85.retryEject = data[9]; //重试弹出标记  0未重试 1重试了一次
                }
            } else {
                _Data85.rfid = data[1]; //RFID
                _Data85.mac = data[2]; //设备MAC地址
                _Data85.status = data[3]; //开锁状态
            }
        }

        return _Data85;
    },

    //解析95数据
    parseData95(data) {
        let _Data95 = null;
        if (data.length < 5) {
            console.info('【蓝牙连接】无效的95响应数据', data);
            return _Data95;
        }
        _Data95 = new Object();
        if (!isArrayFn(data)) {
            _Data95.command = data.substring(8, 10); //指令
            _Data95.rfid = data.substring(10, 18); //RFID
            _Data95.mac = data.substring(18, 30); //设备MAC地址
            _Data95.costTime = data.substring(30, 38); //时间
            _Data95.electrict = parseInt(data.substring(38, 42), 16); //剩余电量
            _Data95.hookStatus = parseInt(data.substring(42, 44), 16); // 1不对 0对
            _Data95.powerOnCount = parseInt(data.substring(44, 48));
            _Data95.chairSwitchSatus = parseInt(data.substring(48, 50), 16);
            _Data95.programRestartTimes = parseInt(data.substring(50, 52), 16); //滴滴两声 0非滴滴，1滴滴两声
            _Data95.programRestartErrCode = parseInt(data.substring(52, 56), 16); //自动修复次数
            _Data95.rfidIsCache = parseInt(data.substring(56, 58), 16);
            _Data95.rfidRepeatCount = parseInt(data.substring(58, 60), 16);
            _Data95.rfidReadErrCode = data.substring(60, 62);
            _Data95.motorStat = data.substring(62, 64);
            _Data95.loseChair = data.substring(64, 66);
            _Data95.unlockErrCode = data.substring(66, 68);
            if (data.length > 72) {
                _Data95.chairIsEjectLose = parseInt(data.substring(68, 70), 16);
            }
            if (data.length > 74) {
                //超出的参数
                _Data95.extVal = data.substring(70, data.length - 2);
            }
            return _Data95;
        }

        _Data95.command = parseInt(data[0]); //指令
        _Data95.rfid = data[1]; //RFID
        _Data95.mac = data[2]; //设备MAC地址
        _Data95.costTime = data[3]; //时间
        _Data95.electrict = parseInt(data[4], 16); //剩余电量
        _Data95.hookStatus = -1;
        _Data95.powerOnCount = -1;
        _Data95.chairSwitchSatus = -1;
        _Data95.programRestartTimes = -1;
        _Data95.programRestartErrCode = -1;

        if (data.length >= 6) {
            _Data95.hookStatus = parseInt(data[5], 16);
        }

        if (data.length >= 7) {
            _Data95.powerOnCount = parseInt(data[6], 16);
        }

        if (data.length >= 8) {
            _Data95.chairSwitchSatus = parseInt(data[7], 16);
        }

        if (data.length >= 9) {
            //滴滴两声
            _Data95.programRestartTimes = parseInt(data[8], 16);
        }

        if (data.length >= 10) {
            //自动修复次数
            _Data95.programRestartErrCode = parseInt(data[9], 16);
        }

        if (data.length >= 11) {
            _Data95.rfidIsCache = parseInt(data[10], 16);
        }
        if (data.length >= 12) {
            _Data95.rfidRepeatCount = parseInt(data[11], 16);
        }
        if (data.length >= 13) {
            _Data95.rfidReadErrCode = data[12];
        }

        if (data.length >= 14) {
            _Data95.motorStat = data[13];
        }
        if (data.length >= 15) {
            _Data95.loseChair = data[14];
        }
        if (data.length >= 16) {
            _Data95.unlockErrCode = data[15];
        }
        if (data.length >= 17) {
            _Data95.chairIsEjectLose = parseInt(data[16], 16);
        }

        if (data.length >= 18) {
            _Data95.box_time = data[17];
        }
        if (data.length >= 19) {
            _Data95.pile_ver = data[18];
        }
        if (data.length >= 20) {
            _Data95.recent_electrict = data[19];
        }

        if (data.length >= 21) {
            var extVal = '';
            var len = data.length;
            for (var i = 20; i < len; i++) {
                extVal += data[i];
                if (i < len - 1) {
                    extVal += ",";
                }
            }
            _Data95.extVal = extVal;
        }

   
        return _Data95;
    },

    parseData98(data) { //新固件/新协议 
        let _Data98 = new Array();
        _Data98.push(data.substring(8, 10));
        _Data98.push(data.substring(10, 14)); //2
        _Data98.push(data.substring(14, 22)); //4
        _Data98.push(data.substring(22, 26)); //2
        _Data98.push(data.substring(26, 34)); //4
        _Data98.push(data.substring(34, 38)); //2
        _Data98.push(data.substring(38, 46)); //4
        _Data98.push(parseInt(data.substring(46, 54), 16) + ''); //4  index7
        _Data98.push(parseInt(data.substring(54, 62), 16) + ''); //4  index8
        _Data98.push(parseInt(data.substring(62, 66), 16) + ''); //2  index9
        _Data98.push(data.substring(66, 68)); //1
        _Data98.push(data.substring(68, 70)); //1
        _Data98.push(data.substring(70, 78)); //4
        _Data98.push(data.substring(78, 80)); //1
        this.data98 = _Data98
    },

    //解析宜家陪护椅驱动数据
    parsePeihuyiValue: function (receiveData) {
        let that = this
        var recArr = new Int8Array(receiveData.value);
        let decryptData = BleTool.peihuyiAesDecrypt(recArr);

        BleTool.belLog("value is" + decryptData), BleTool.belLog("value.toString().indexOf(getTokenPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.getTokenPrefix)),
            BleTool.belLog("value.toString().indexOf(queryLockStatusPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.queryLockStatusPrefix)),
            BleTool.belLog("value.toString().indexOf(queryLockBatteryPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.queryLockBatteryPrefix)),
            BleTool.belLog("value.toString().indexOf(unlockPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.unlockPrefix)),
            BleTool.belLog("value.toString().indexOf(lockPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.lockPrefix)),
            BleTool.belLog("value.toString().indexOf(deviceDisconnectPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.deviceDisconnectPrefix)),
            BleTool.belLog("value.toString().indexOf(unknowCmdPrefix) is" + decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.unknowCmdPrefix)),
            0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.getTokenPrefix) ? that.parsePeihuyiGetToken(decryptData) :
            0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.queryLockStatusPrefix) ? that.parsePeihuyiQueryLockStatus(decryptData) :
            0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.queryLockBatteryPrefix) ? that.parsePeihuyiQueryLockBattery(decryptData) :
            0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.unlockPrefix) ? that.parsePeihuyiUnlock(decryptData) :
            0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.lockPrefix) || 0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.lockPrefix2) ? that.parsePeihuyiLock(decryptData) :
            0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.deviceDisconnectPrefix) ? that.parsePeihuyiDeviceDisconnect(decryptData) : 0 == decryptData.toString().indexOf(BleTool.peihuyiBleVariable.dataPrefix.unknowCmdPrefix) ? that.parsePeihuyiUnknownCmd(decryptData) : that.parsePeihuyiStartBleCommErrCallback("命令异常");
    },
    //解析获取到的令牌信息
    parsePeihuyiGetToken: function (e) {
        this._DataOneMorePhyLock = new Object()
        for (var o = 3; o < 7; o++) BleTool.peihuyiBleVariable.token[o - 3] = e[o];
        setTimeout(function () {
            BleTool.queryPeihuyiBattery();
        }, 200);
    },
    //解析one more 陪护椅的锁电量信息
    parsePeihuyiQueryLockBattery: function (e) {
        BleTool.belLog("parseQueryLockBattery");
        var a = e[3];
        this._DataOneMorePhyLock.mac = BleTool.macId; //设备MAC地址
        this._DataOneMorePhyLock.electrict = e[3];
        //获取完电量后获取锁状态
        BleTool.queryPeihuyiLockStatus();

        BleTool.belLog("lockBattery is" + a);
    },
    //解析宜家陪护椅锁状态
    parsePeihuyiQueryLockStatus: function (e) {
        BleTool.belLog("parseQueryLockStatus", e);
        var halStatus = e[3],
            localLockStatus = e[4];
        BleTool.belLog("parseQueryLockStatus halStatus is" + halStatus + " localLockStatus = " + localLockStatus);

        this._DataOneMorePhyLock = new Object();
        this._DataOneMorePhyLock.command = 'OM050E'; //指令 查询锁状态
        this._DataOneMorePhyLock.rfid = '00000000'; //RFID
        this._DataOneMorePhyLock.costTime = '0'; //时间
        //1表示锁舌弹出，对应锁钩开关应该为0
        let lockStatus = parseInt(localLockStatus, 16);
        this._DataOneMorePhyLock.hookStatus = lockStatus == 1 ? 0 : 1; // 1不对 0对
        this._DataOneMorePhyLock.powerOnCount = -1;
        //磁开关0表示未锁住，1表示锁住，对应插入开关
        this._DataOneMorePhyLock.chairSwitchSatus = parseInt(halStatus, 16); //0未锁住 1已锁住
        this._DataOneMorePhyLock.programRestartTimes = -1; //滴滴两声 0非滴滴，1滴滴两声
        this._DataOneMorePhyLock.programRestartErrCode = -1; //自动修复次数
        this._DataOneMorePhyLock.rfidIsCache = -1;
        this._DataOneMorePhyLock.rfidRepeatCount = -1;
        this._DataOneMorePhyLock.rfidReadErrCode = '';
        this._DataOneMorePhyLock.motorStat = '';
        this._DataOneMorePhyLock.loseChair = '';
        this._DataOneMorePhyLock.unlockErrCode = '';

        this._DataOneMorePhyLock.chairIsEjectLose = 0;
        this._DataOneMorePhyLock.box_time = '';
        this._DataOneMorePhyLock.recent_electrict = -1;
        this._DataOneMorePhyLock.extVal = '';
    },

    //解析one more陪护椅开锁命令返回值
    parsePeihuyiUnlock: function (e) {
        console.log("parseUnlock");
        this._DataOneMorePhyLock.unlock = new Object()
        this._DataOneMorePhyLock.unlock.noEject = e[3];
        setTimeout(function () {
            BleTool.closeBLEConnection(BleTool.deviceId)
        }, 1e4);
    },

    //解析one more 陪护椅归还锁住命令返回值
    parsePeihuyiLock: function (e) {
        console.log("parseLock");
        if (0 == e[3]) {
            console.log("one more 陪护椅锁成功");
        } else {
            console.log("one more 陪护椅锁失败");
        }
    },

    //解析one more陪护椅断开连接
    parsePeihuyiDeviceDisconnect: function (err) {
        console.log("断开连接:", err);
    },
    //解析one more陪护椅未知命令
    parsePeihuyiUnknownCmd: function (e) {
        console.log("unknowCmdPrefix");
    },
    //解析one more陪护椅异常命令
    parsePeihuyiStartBleCommErrCallback: function (err) {
        console.log("命令异常错误:", err);
    }

}

/**
 * 创建发送的命令信息
 * @param {*} cmdId 
 * @param {*} params 
 * @param {*} version 
 */
function createSendMessage(cmdId, params, version) {
    if (!bleData.blePwd) {
        wx.showModal({
            title: '提示',
            content: '秘钥不存在',
            showCancel: false,
            success(res) {}
        })
        return
    }
    if (!params) {
        params = '00'
    }
    BleTool.belLog("变长数据包内容：" + params);
    ++BleTool.cmdSeq;
    var seq = BleTool.cmdSeq.toString(16).toUpperCase();
    seq = padLast(seq, 2);
    var len = '12'; //数据定长为18个字节
    len = padLast(len, 2);
    cmdId = padLast(cmdId, 2);

    var bMagicNumber = 'F5';
    var bVer = version && version != 'undefined' ? version : '01';
    var nLength = len;
    var nCmdId = cmdId;
    var nSeq = seq;

    var result1 = bMagicNumber + nLength + bVer + nSeq + nCmdId;
    params = padLast(params, (36 - result1.length)); //额外参数补齐，总长20字节（包含校验码2个字节）
    let content = bVer + nSeq + nCmdId + params;
    BleTool.belLog("cmd:" + nCmdId + ";content:" + content);
    //加密      
    let msgPwd = AESUtil.aesEncryptByPwd(bleData.blePwd, content);
    BleTool.belLog("cmd密文:" + nCmdId + ";content:" + msgPwd);

    var result2 = bMagicNumber + nLength + msgPwd;
    BleTool.belLog("加密数据--result2=", result2);
    let validateCode = CRC16.ToModbusCRC16(result2);
    return result2 + validateCode;
}

//校验接受到的数据crc16码是否正确
function validateCrc16Code(hexData) {
    let data = hexData.substring(0, hexData.length - 4);
    let vCode = hexData.substring(hexData.length - 4);
    let validateCode = CRC16.ToModbusCRC16(data);
    pad(validateCode, 4);
    if (validateCode != vCode) {
        BleTool.belLog("【蓝牙连接】数据CRC16校验失败，无法处理", validateCode);
        return false;
    }
    return true;
}

function pad(num, n) {
    var len = num.toString().length;
    while (len < n) {
        num = '0' + num;
        len++;
    }
    return num;
}

function padLast(num, n) {
    var len = num.toString().length;
    while (len < n) {
        num = num + '0';
        len++;
    }
    return num;
}

function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}

//将设备发的数据转换为16进制
function buf2hex(buffer) {
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
}

function isArrayFn(value) {
    BleTool.belLog('typeOf-data', typeof (value), Array.isArray(value));
    if (typeof Array.isArray === "function") {
        return Array.isArray(value);
    } else {
        return Object.prototype.toString.call(value) === "[object Array]";
    }
}





exports.BleTool = BleTool